﻿using FreeScheduler;
using IGeekFan.AspNetCore.Knife4jUI;
using Simple.WebAi.Extensions;

namespace Simple.WebAi
{
    public class Startup
    {
        public IConfiguration Configuration { get; }
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();

            // 注册健康状态检查
            services.AddHealthChecks();

            // 允许所有来源
            services.AddCors();

            // 注册Controllers
            services.AddControllers();

            // 注册Swagger
            services.AddSwaggerGen();

            // 注册FreeSql
            services.AddFreeSql();

            // 注册FreeRedis
            services.AddFreeRedis();

            // 注册Services
            services.AddServices();

            // 注册
            services.AddTencentCloudServices();

            // 添加微信ApiClient
            services.AddWechatApiClient();

            // 注册FreeScheduler 任务调度
            services.AddFreeScheduler();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // 使用Swagger UI
            app.UseSwaggerUI();

            // 使用健康状态检查中间件
            app.UseHealthChecks("/health");

            // 使用StaticFiles
            app.UseStaticFiles();

            // 使用Routing
            app.UseRouting();

            // UseAuthentication
            app.UseAuthentication();

            // 使用允许跨域
            app.UseCors(options =>
            {
                options.SetIsOriginAllowed(_ => true)
                       .AllowCredentials()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            });

            // UseAuthorization
            app.UseAuthorization();

            // 使用UseKnife4UI
            app.UseKnife4UI(c =>
            {
                c.RoutePrefix = string.Empty; ; // serve the UI at root
                c.SwaggerEndpoint("/v1/api-docs", Configuration!["Swagger:Title"]);
            });

            // 使用FreeScheduler 任务调度 UI
            app.UseFreeSchedulerUI("/freescheduler/");

            // 使用MapControllers
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();

                //绑定UseKnife4UI
                endpoints.MapSwagger("{documentName}/api-docs");
            });
        }
    }
}
